//
//  BindingChange.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/6/12.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import RKDropdownAlert
class BindingChange: HMViewController,UITextFieldDelegate {

    
    
    
    // MARK: - 变量
    var oldPhone: String?  //旧手机号
    var answerId: String?  //密保问题ID
    var answerValue: String? //密保问题答案
    var signUpPhone: String? // 注册手机号
    
    
    
    var _maskView: UIView?
    var _maskView2: UIView?
    var pickerAry: Array<Any>?
    
    // MARK: - 常量
    let bgImg = UIImageView()
    let securityContrainer = UIView()
    let securityUntie = UIButton()
    let problemButton = UIButton()
    let auxiliaryUntie = UIButton()
    let answer = UITextField()
    let friendPhone = UITextField()
    let smsField = UITextField()
    let smsButton = UIButton()
    let nextStep = UIButton()
    
    let auxiliaryContainer = UIView()
   
    let line1 = UIView()
    let line2 = UIView()
    let line3 = UIView()
    let line4 = UIView()
    let line5 = UIView()
    let lineVertical = UIView()
    let line6 = UIView()
    let _sing = UIImageView() //箭头
     // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        _maskView2 =  UIView.createMaskView(this: self, action: #selector(onMark))
        keyBordNotification(this: self, aShow: #selector(keyBoardWillShow(_:)), aHide: #selector(keyBoardWillHide(_:)))
        //请求

    }
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    // MARK: - 配置view
    override func setupView() {
        if(self._signStr != "") {
            self.title = self._signStr
        }
        view.backgroundColor = UIColor.white
        
        
        view.addSubview(securityUntie)
        view.addSubview(securityContrainer)
        securityContrainer.addSubview(line1)
        securityContrainer.addSubview(problemButton)
        problemButton.addSubview(_sing)
        securityContrainer.addSubview(line2)
        securityContrainer.addSubview(answer)
        securityContrainer.addSubview(line3)

        
        view.addSubview(auxiliaryUntie)
        view.addSubview(auxiliaryContainer)
        auxiliaryContainer.addSubview(line4)
        auxiliaryContainer.addSubview(friendPhone)
        auxiliaryContainer.addSubview(line5)
        auxiliaryContainer.addSubview(smsField)
        auxiliaryContainer.addSubview(smsButton)
        auxiliaryContainer.addSubview(lineVertical)
        auxiliaryContainer.addSubview(line6)
        
        view.addSubview(nextStep)
        
        let xSecurity = 20.0
        let ySecurity = 10.0
        let wSecurity = Double(view.wWidth - 40.0)
        let hSecurity = 44.0
        
        securityUntie.frame = CGRect(x: xSecurity, y: ySecurity, width: wSecurity, height: hSecurity)
        if (_signStr == "更改绑定"){
          securityUntie.setTitle("密保问题改绑", for: .normal)
        }else{
          securityUntie.setTitle("设置密保问题", for: .normal)
        }
        securityUntie.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        securityUntie.setTitleColor(UIColor.black, for: .normal)
        securityUntie.isSelected = true
        securityUntie.tag = 1000
        securityUntie.setImage(UIImage.init(named: "check_false.png"), for: .normal)
        securityUntie.setImage(UIImage.init(named: "check_true.png"), for: .selected)
        securityUntie.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10)
        securityUntie.addTarget(self, action: #selector(checkUntie), for: .touchUpInside)
        

        securityContrainer.frame = CGRect(x: xSecurity, y:  Double(securityUntie.wHeight) + ySecurity, width: wSecurity, height: 90)
        securityContrainer.alpha = 1
        
        line1.topAlign(view: securityContrainer, predicate: "0")
        line1.backgroundColor = UIColor.RGBA(r: 237, g: 240, b: 242, a: 1)
        line1.heightConstrain(predicate: "1")
        line1.leadingAlign(view: view, predicate: "20")
        line1.trailingAlign(view: view, predicate: "-20")
        
        
        problemButton.topVertically(view: line1, predicate: "0")
        problemButton.leadingAlign(view: view, predicate: "20")
        problemButton.trailingAlign(view: view, predicate: "-20")
        problemButton.height(view: securityUntie)
        problemButton.setTitleColor(UIColor.gray, for: .normal)
        problemButton.setTitle("请选择要回答的问题", for: .normal)
        problemButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        problemButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0)
        problemButton.addTarget(self, action: #selector(self.showPicker(_:)), for: .touchUpInside)
        _sing.imgName(name: "xianjiang")
        _sing.centerYAlign(view: problemButton)
        _sing.trailingAlign(view: problemButton, predicate: "-10")
        _sing.heightConstrain(predicate: "25")
        _sing.widthConstrain(predicate: "25")
        
        
        
        line2.topVertically(view: problemButton, predicate: "0")
        line2.backgroundColor =   line1.backgroundColor
        line2.height(view: line1) //heightConstrain(predicate: "1")
        line2.leadingAlign(view: view, predicate: "20")
        line2.trailingAlign(view: view, predicate: "-20")
        
        

        
        answer.topVertically(view: line2, predicate: "0")
        answer.leadingAlign(view: view, predicate: "20")
        answer.trailingAlign(view: view, predicate: "-20")
        answer.height(view: securityUntie)
        let leftView = UIView()
        leftView.frame = CGRect.init(x: 0, y: 0, width: 15, height: 0)
        leftView.backgroundColor = UIColor.red
        answer.leftView = leftView
        answer.leftViewMode  = UITextFieldViewMode.always
        answer.placeholder = "请输入答案"
        answer.tag = 100

        line3.topVertically(view: answer, predicate: "0")
        line3.backgroundColor =   line1.backgroundColor
        line3.height(view: line1)
        line3.leadingAlign(view: view, predicate: "20")
        line3.trailingAlign(view: view, predicate: "-20")
       
        
    
        // 亲友绑定部分
        if(self._signStr == "更改绑定") {
            
            auxiliaryUntie.frame = CGRect(x: xSecurity, y: Double(securityContrainer.frame.maxY), width: wSecurity, height: hSecurity)
            auxiliaryUntie.setTitle("亲友辅助改绑", for: .normal)
            auxiliaryUntie.isSelected = false
            auxiliaryUntie.tag = 1001
            auxiliaryUntie.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
            auxiliaryUntie.setTitleColor(UIColor.black, for: .normal)
            auxiliaryUntie.setImage(UIImage.init(named: "check_true.png"), for: .selected)
            auxiliaryUntie.setImage(UIImage.init(named: "check_false.png"), for: .normal)
            auxiliaryUntie.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10)
            auxiliaryUntie.addTarget(self, action: #selector(checkUntie), for: .touchUpInside)
            view.bringSubview(toFront: auxiliaryUntie)

            
            auxiliaryContainer.frame = CGRect(x: xSecurity, y: Double(auxiliaryUntie.frame.maxY), width: wSecurity, height: 0)
            auxiliaryContainer.alpha = 0
            
            line4.topAlign(view: auxiliaryContainer, predicate: "0")  //topVertically(view: auxiliaryUntie, predicate: "0")
            line4.backgroundColor =   line1.backgroundColor
            line4.height(view: line1)
            line4.leadingAlign(view: view, predicate: "20")
            line4.trailingAlign(view: view, predicate: "-20")

            friendPhone.topVertically(view: line4, predicate: "0")
            friendPhone.leadingAlign(view: view, predicate: "20")
            friendPhone.trailingAlign(view: view, predicate: "-20")
            friendPhone.height(view: securityUntie)
            let leftView1 = UIView()
            leftView1.frame = CGRect.init(x: 0, y: 0, width: 15, height: 0)
            friendPhone.leftView = leftView1
            friendPhone.leftViewMode  = UITextFieldViewMode.always
            friendPhone.placeholder = "请输入辅助亲友的手机"
            friendPhone.tag = 101
            friendPhone.delegate = self

            line5.topVertically(view: friendPhone, predicate: "0")
            line5.backgroundColor =   line1.backgroundColor
            line5.height(view: line1)
            line5.leadingAlign(view: view, predicate: "20")
            line5.trailingAlign(view: view, predicate: "-20")

            
            smsField.topVertically(view: line5, predicate: "0")
            smsField.leadingAlign(view: view, predicate: "35")
            smsField.trailingAlign(view: view, predicate: "-20")
            smsField.height(view: securityUntie)
            smsField.tag = 102
            smsField.placeholder = "验证码"
            smsField.delegate = self
            smsField.setValue(UIFont.systemFont(ofSize: 17), forKeyPath: "_placeholderLabel.font")
            smsField.setValue(UIColor.RGBA(r: 199, g: 199, b: 204, a: 1), forKeyPath: "_placeholderLabel.textColor")

            
            smsButton.topVertically(view: line5, predicate: "0")
            smsButton.trailingAlign(view: smsField, predicate: "0")
            smsButton.height(view: securityUntie)
            smsButton.widthConstrain(predicate: "100")
            smsButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            smsButton.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
            smsButton.addTarget(self, action: #selector(getSMSClick), for: .touchUpInside)
            smsButton.setTitle("获取验证码", for: .normal)


            lineVertical.topVertically(view: line5, predicate: "10")
            lineVertical.leadingAlign(view: smsButton, predicate: "0")
            lineVertical.heightConstrain(predicate: "32")
            lineVertical.backgroundColor = line1.backgroundColor
            lineVertical.widthConstrain(predicate: "1")


            line6.topVertically(view: smsField, predicate: "0")
            line6.leadingAlign(view: view, predicate: "20")
            line6.trailingAlign(view: view, predicate: "-20")
            line6.backgroundColor = line1.backgroundColor
            line6.height(view: line1)
        }

        
        if (_signStr == "更改绑定"){
           nextStep.frame = CGRect(x: 60, y: auxiliaryContainer.frame.maxY + 15, width: view.wWidth - 120, height: 44)
        }else {
           nextStep.frame = CGRect(x: 60, y: securityContrainer.frame.maxY + 15, width: view.wWidth - 120, height: 44)
        }
        nextStep.backgroundColor =   configure.shareConfigure.HMColor3
        nextStep.setTitle("下一步", for: .normal)
        nextStep.setTitleColor(UIColor.white, for: .normal)
        nextStep.addTarget(self, action: #selector(nextStepClick), for: .touchUpInside)
        nextStep.layer.cornerRadius = 20
    
    }
    
    
    @objc func checkUntie (sender: UIButton) {
            if sender.tag == 1000 {
                securityUntie.isSelected = true
                auxiliaryUntie.isSelected = false
                UIView.animate(withDuration: 0.4, animations: {
                    self.auxiliaryContainer.frame.size.height = 0
                    self.auxiliaryContainer.alpha = 0
                   
                    self.securityContrainer.frame.size.height = 90
                    self.securityContrainer.alpha = 1
                    self.auxiliaryUntie.frame.origin.y = self.securityContrainer.frame.maxY
                })
              
                
            }else {
                securityUntie.isSelected = false
                auxiliaryUntie.isSelected = true
                answer.text = ""
                UIView.animate(withDuration: 0.4, animations: {
                    self.securityContrainer.frame.size.height = 0
                    self.securityContrainer.alpha = 0
                    
                    self.auxiliaryContainer.frame.size.height = 90
                    self.auxiliaryContainer.alpha = 1
                    self.auxiliaryUntie.frame.origin.y = self.securityUntie.frame.maxY
                    self.auxiliaryContainer.frame.origin.y = self.auxiliaryUntie.frame.maxY
                })
            }
        setButtonSytle()
    }
    @objc func showPicker (_ : UIButton) {
        
         self._maskView =  UIView.createMaskView(this: self, action: #selector(clickMark))
        let app =  UIApplication.shared.delegate as! AppDelegate
        app.window?.addSubview(self._maskView!)
        var ary1 = Array<String>()
        for dic in self.pickerAry! {
            let _dic = dic as! NSDictionary
             ary1.append(_dic["question"] as! String)
        }
        HMPickerView.sharePicker.delegate = self
        HMPickerView.creator(app.window!, picker: ["Ary" : ary1])
    }

    
    @objc func nextStepClick() {
        if(self._signStr == "更改绑定"){
            
            let _str: String = self.friendPhone.text! as String
            let _signUp = SignUp()
            _signUp._signStr = "改绑验证"
            _signUp.oldPhone = self.oldPhone
          
            if  securityUntie.isSelected == true {
                if self.answerId != nil {
                    _signUp.answerId = self.answerId
                    _signUp.answerValue = self.answer.text
                    self.pushViewController(_signUp)
                }else {
                    RKDropdownAlert.title("请注意～", message:"请重选择密保问题~", backgroundColor: UIColor.green, textColor: UIColor.red, time: 5)
                }
            }else {
    
                if (String.isTelNumber(num: _str) == true) {
                    _signUp.friendCode = self.smsField.text
                    _signUp.friendPhone = _str
                     self.pushViewController(_signUp)
                }else {
                    RKDropdownAlert.title("请注意～", message:"请重输入正确的手机格式~", backgroundColor: UIColor.green, textColor: UIColor.red, time: 5)
                }

            }

        }else {
          let _userinfo = Userinfo()
             _userinfo.signUpPhone = self.signUpPhone
             _userinfo.question = self.problemButton.titleLabel?.text
             _userinfo.answerValue = self.answer.text
          self.pushViewController(_userinfo)
        }
    }
    /**
     获取验证码
     */
    @objc func getSMSClick(sender: UIButton) {

        let _str = friendPhone.text! as String
        if (String.isTelNumber(num: _str) == true) {
            
            sender.countdownButton(second: 60, title: "获取验证码")
            NetRequestTool.request(url: "sms-code/rebind-friend/send", parameters: ["oldPhone": self.oldPhone!,"friendPhone":_str], success: { (json) in
                self.showToast(message: json["msg"].stringValue)
            }, fail: { (error, msg) in
                print("------------ \(error)")
            }) {}
        }else {
            RKDropdownAlert.title("请注意～", message:"手机格式错误，请重新输入", backgroundColor: UIColor.orange, textColor: UIColor.white, time: 5)
        }
        
        
    }
    // UITapGestureRecognizer
    @objc func onMark(send: UITapGestureRecognizer) {
        _maskView2?.removeFromSuperview()
        self.smsField.resignFirstResponder()//结束编辑状态
        self.answer.resignFirstResponder()
        self.friendPhone.resignFirstResponder()//结束编辑状态
    }
    @objc func clickMark(sender: UITapGestureRecognizer) {
         HMPickerView.hidePickeView()
        _maskView?.removeFromSuperview()
    }
    
    
    /**
     键盘监控
     */
    @objc func keyBoardWillShow(_ notification: Notification){
        self.view.window?.addSubview(_maskView2!)
//        print("------->>keyBoardWillShow")
    }
    
    @objc func keyBoardWillHide(_ notification: Notification){
//        print("------->>keyBoardWillHide")
        self.setButtonSytle()
    }
    // 设置按钮表现效果
    func setButtonSytle()  {
        //判断是否开启按钮
        if securityUntie.isSelected == true {
            
            if (self.answer.text!.count > 0)  {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
            }else {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
            }
            
        }else {
            if (self.smsField.text!.count > 0 && self.friendPhone.text!.count > 0)  {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: true)
            }else {
                openButtonRecognition(setStyleBtn: self.nextStep, isOpen: false)
            }
        }
        
        
       
    }
    
    // 点键盘按钮
//    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//        if textField.tag == 102 {
//            self.smsField.becomeFirstResponder()
//        }else {
//
//        }
//        return true
//    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        if textField.tag == 100 {
            return (len <= 40)
        }else if textField.tag == 101 {
            return (len <= 11)
        }else {
            return (len <= 6)
        }
    }
}

extension BindingChange: HMPickerViewDelegate {
    func cancel() {
        self._maskView?.removeFromSuperview()
    }
    
    func selectValue(value: String, row: Int, component: Int) {
        //一个cell刷新
        let dic = self.pickerAry![row] as! Dictionary<String,Any>
        let _str = dic["question"] as! String
        self.answerId = dic["id"] as? String
        self.problemButton.setTitle(_str, for: .normal)
         HMPickerView.hidePickeView()
        self.cancel()
    }
}
